package edu.sias.chat.config;

import edu.sias.framework.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.List;

@Slf4j
@Component
public class TokenSubprotocolConfigurator extends ServerEndpointConfig.Configurator {

    private static TokenService tokenService;

    @Autowired
    public void setTokenService(TokenService tokenService) {
        TokenSubprotocolConfigurator.tokenService = tokenService;
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        List<String> subprotocols = request.getHeaders().get("Sec-WebSocket-Protocol");
        if (subprotocols == null || subprotocols.isEmpty()) {
            throw new IllegalArgumentException("未提供 Token");
        }
        String token = subprotocols.get(0);
        String username = tokenService.getUsernameFromToken(token);

        if (username == null) {
            throw new RuntimeException("Token 无效");
        }
        sec.getUserProperties().put("username", username);
        response.getHeaders().put("Sec-WebSocket-Protocol", subprotocols);
    }
}
